package com.xijia.xj.observer.subject;

import com.alibaba.fastjson.JSONObject;
import com.xijia.xj.observer.ObServer;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * 观察者容器， listObServer = 所有的观察类
 * @author wangsong
 * @mail 1720696548@qq.com
 * @date 2020/9/2 0002 21:22
 * @version 1.0.0
 */
@Component
public class XjSubject {

    /**
     * 类型 ObServer
     */
    private List<ObServer> listObServer = new ArrayList<>();
    /**
     * 线程池
     */
    private ExecutorService executorService;


    public XjSubject() {
        executorService = Executors.newFixedThreadPool(10);
    }

    /**
     * 新增ObServer
     *
     * @param obServer
     */
    public void addObServer(ObServer obServer) {
        listObServer.add(obServer);
    }

    /**
     * 通知给所有的观察者
     *
     * @param jsonObject
     */
    public void notifyObServer(JSONObject jsonObject) {
        for (ObServer obServer : listObServer) {
            // 单独开启线程异步通知
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    obServer.sendMsg(jsonObject);
                }
            });
        }
    }
}
